#include "gd32f30x.h"
#include "adc.h"
#include "type.h"
#include "systick.h"
/**
 * PA4 adc resolution test
 * Alternate: ADC01_IN4
*/

void pa4_adc_resolution_config(void)
{

    //配置PA4 ADC引脚
	rcu_periph_clock_enable(RCU_GPIOA);
	gpio_init(GPIOA, GPIO_MODE_AIN, GPIO_OSPEED_50MHZ, GPIO_PIN_4); 
	
	/* enable ADC1 clock */
	rcu_periph_clock_enable(RCU_ADC1);
	/* config ADC clock */
	rcu_adc_clock_config(RCU_CKADC_CKAPB2_DIV8);
   /* reset ADC */
    adc_deinit(ADC1);
 
    /* ADC mode config */
    adc_mode_config(ADC_MODE_FREE); 
    /* ADC continous function enable */
    adc_special_function_config(ADC1, ADC_CONTINUOUS_MODE, ENABLE); 
   
    /* ADC data alignment config */
    adc_data_alignment_config(ADC1, ADC_DATAALIGN_RIGHT);
    /* ADC resolusion 6B */
    //adc_resolution_config(ADC1, ADC_RESOLUTION_6B); 
    /* ADC channel length config */
    adc_channel_length_config(ADC1, ADC_REGULAR_CHANNEL, 1);

    /* ADC regular channel config */
    adc_regular_channel_config(ADC1, 0, ADC_CHANNEL_4, ADC_SAMPLETIME_55POINT5);

    /* ADC trigger config */
    adc_external_trigger_source_config(ADC1, ADC_REGULAR_CHANNEL, ADC0_1_2_EXTTRIG_REGULAR_NONE); 
    adc_external_trigger_config(ADC1, ADC_REGULAR_CHANNEL, ENABLE);

    /* enable ADC interface */
    adc_enable(ADC1);  
    delay_1ms(1);
    /* ADC calibration and reset calibration */
    adc_calibration_enable(ADC1);
    /* enable ADC interface */    
	//	adc_software_trigger_enable(ADC0,ADC_REGULAR_CHANNEL);

    adc_software_trigger_enable(ADC1, ADC_REGULAR_CHANNEL);
}

void pa4_adc_resolution_test(void)
{
    uint16_t adc_value;
    pa4_adc_resolution_config();
    delay_1ms(1000);
    delay_1ms(1000);

    while(1)
    {        
        adc_flag_clear(ADC1, ADC_FLAG_EOC);
        while(SET != adc_flag_get(ADC1, ADC_FLAG_EOC)){
        }
        adc_value = ADC_RDATA(ADC1);        
        printf("Get ADC Value: %d\r\n", adc_value * 3300 / 4095);
        printf("\r\n ***********************************\r\n");
        delay_1ms(1000);
    }
}